package Userjava.Userdao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

public class DButil {

    static  String driver="com.mysql.jdbc.Driver";
    static  String url="jdbc:mysql://localhost:3306/newsmanagersystem?serverTimezone=UTC";
    static  String user="root";
    static  String pwd="123456";

    static  ThreadLocal<Connection> threadLocal=new ThreadLocal<>();
            public static Connection getConnection(){
                Connection conn=threadLocal.get();
                try {

                   if (conn==null){
                       Class.forName(driver);
                          conn=DriverManager.getConnection(url,user,pwd);
                           threadLocal.set(conn);
                   }
                } catch (SQLException e) {
                    e.printStackTrace();
                } catch (ClassNotFoundException e) {
                    e.printStackTrace();
                }
                return conn;
            }
            public static int executeUpdate(String sql,Object[] param) throws SQLException {
                Connection conn=getConnection();
                PreparedStatement pre=null;
                try {
                    pre = conn.prepareStatement(sql);
                    if (param != null) {
                        for (int i = 0; i < param.length; i++) {
                            pre.setObject(i + 1, param[i]);
                        }
                        return pre.executeUpdate();
                    }
                }catch (SQLException e){
                   throw  e;
                }finally {
                        pre.close();
                }
                return -1;
            }
            public static  void setAutoCommit(boolean falg){
                try {
                    getConnection().setAutoCommit(falg);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }

            public  static  void commit() {
                try {
                    getConnection().commit();
                    setAutoCommit(true);
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
            public static  void rollback() {
                try {
                    getConnection().rollback();
                    setAutoCommit(true);
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
}
